//
//  FeedbackCell.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/8.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "FeedbackCell.h"
#import "UserInfoController.h"
#import "ZCTTMLEmojiLabel.h"
#import "SVWebViewController.h"

@interface FeedbackCell()<ZCTTMLEmojiLabelDelegate>{
    
}

@end

@implementation FeedbackCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    // Initialization code
     self.userInteractionEnabled = YES;
    _imgAvatar.layer.cornerRadius = 22.0f;
    _imgAvatar.layer.masksToBounds = YES;
    
    [_labTitle setFont:FontFiftent];
    _labTitle.numberOfLines = 0;
    [_labTitle setTextColor:UIColorFromRGB(Text6Color)];
    
    
    [_labName setFont:FontFiftent];
    [_labName setTextColor:UIColorFromRGB(TextSizeOneColor)];
    
    [_btnZan.titleLabel setFont:ListElevenFont];
    _btnZan.layer.borderColor = UIColorFromRGB(BorderLineColor).CGColor;
    [_btnZan setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
    [_btnZan setImage:[UIImage imageNamed:@"收藏 小按钮"] forState:0];
    _btnZan.hidden = YES;
    
    [_labTime setFont:FontThirteen];
    [_labTime setTextColor:UIColorFromRGB(BgLineColor)];
    _commentView.backgroundColor = UIColorFromRGB(BgSystemColor);
    _commentView.layer.cornerRadius = 3.0f;
    _commentView.layer.masksToBounds = YES;
    
    _imgAvatar.userInteractionEnabled = YES;
    _labName.userInteractionEnabled = YES;
   
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarClick:)];
    [_imgAvatar addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarClick:)];
    [_labName addGestureRecognizer:tap2];
}

-(void)avatarClick:(UITapGestureRecognizer *) tap{
    
    UserInfoController *vc = [[UserInfoController alloc] init];
    vc.user_id = _tempModel.user_info.user_id;

    if(_delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
        NSLog(@"LLLLLLLLLL");
        [self.delegate onCellItemClick:ZZClickOpenVC obj:vc];
    }
}

-(void) moreComment:(UITapGestureRecognizer *) tap{
    
}


-(void)dataToView:(FeedBackEntity *)topic{
    _tempModel = topic;
    
    [_labName setText:topic.user_info.user_name];
//    [_labTitle setText:topic.message];
    [self addLinkMessage:_labTitle text:topic.message];
    
    [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(topic.user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    
    [_btnZan setTitle:convertToString(topic.count) forState:0];
    
    [self autoWidthOfLabelHegith:_labTitle with:ScreenWidth - 75-20];
    
    [self addCommentView:topic.list fy:CGRectGetMaxY(_labTitle.frame)+(topic.list.count == 0 ? 0 : 10)];
    
    [self setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_commentView.frame)+10)];
}

-(UIImageView *)createImageView{
    UIImageView *imgView = [[UIImageView alloc] init];
    [imgView setContentMode:UIViewContentModeScaleAspectFill];
    imgView.clipsToBounds = YES;
    return imgView;
}

-(UILabel *) createLabel{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setTextAlignment:NSTextAlignmentLeft];
    [label setFont:FontThirteen];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setNumberOfLines:0];
    return label;
}

-(void)addCommentView:(NSMutableArray *) array fy:(CGFloat) y{
    [_commentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat iy = 10;
    if(array.count == 0){
        iy = 0;
    }
    CGFloat maxWidth = ScreenWidth - 74 - 20 - 20;
    for (FeedBackEntity *entity in array) {
//        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, iy, maxWidth, 0)];
//        [label setTextAlignment:NSTextAlignmentLeft];
//        [label setFont:FontThirteen];
//        label.numberOfLines = 0;
//        [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
//        [label setBackgroundColor:UIColor.clearColor];
//        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:%@",entity.user_info.user_name,[ZZCoreTools replaceMessageEmoji:entity.message]]];
//        CGFloat len = [NSString stringWithFormat:@"%@:",entity.user_info.user_name].length;
//        [string addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(BgTitleColor) range:NSMakeRange(0, len)];
//
//        [string addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(Text6Color) range:NSMakeRange(len, string.length - len)];
//        label.attributedText = string;
        
        
        ZCTTMLEmojiLabel *label = [self createLinkLabel:iy w:maxWidth];
        
        NSString *text = [NSString stringWithFormat:@"<a href=\"name://\">%@:</a>%@",entity.user_info.user_name,entity.message];
        
        [self addLinkMessage:label text:text len:entity.user_info];
        
        CGSize s = [self autoWidthOfLabelHegith:label with:maxWidth];
        
        iy = s.height + iy + 7;
        [_commentView addSubview:label];
        
    }
    
    if(array.count > 4){
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, iy, maxWidth, 21)];
        [label setTextAlignment:NSTextAlignmentLeft];
        [label setFont:FontThirteen];
        [label setTextColor:UIColorFromRGB(Text6Color)];
        [label setBackgroundColor:UIColor.clearColor];
        [label setText:@"查看全部评论..."];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreComment:)];
        [label addGestureRecognizer:tap];
        [_commentView addSubview:label];
        iy = iy + 21 + 10;
    }
    
    [_commentView setFrame:CGRectMake(75, y, ScreenWidth - 20 - 75, iy)];
    
}



/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

- (CGSize )autoWidthOfLabelHegith:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}


-(ZCTTMLEmojiLabel *)createLinkLabel:(CGFloat) y w:(CGFloat ) maxWidth{
    ZCTTMLEmojiLabel *label = [[ZCTTMLEmojiLabel alloc] initWithFrame:CGRectMake(10, y, maxWidth, 0)];
    [label setTextAlignment:NSTextAlignmentLeft];
    label.numberOfLines = 0;
    [label setFont:FontThirteen];
    [label setTextColor:UIColorFromRGB(Text6Color)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setLinkColor:UIColorFromRGB(TextLinkColor)];
    [label setDelegate:self];
    label.userInteractionEnabled = YES;
    
    return label;
}

-(void)addLinkMessage:(ZCTTMLEmojiLabel *) label text:(NSString *)text len:(User *) user{
    text = [ZZCoreTools replaceMessageEmoji:text];
    NSString *sugguestText = [ZZCoreTools transformString:text];
    NSMutableDictionary *sugguestDict = [label getTextADict:sugguestText];
    UIColor *color = UIColorFromRGB(Text6Color);
    if([user.is_vip intValue] == 1){
        color = UIColorFromRGB(BgTitleColor);
    }
    if(sugguestDict){
        if(user != nil){
            [label setText:sugguestDict[@"text"] afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
                //文字颜色
                [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName
                                                value:color
                                                range:NSMakeRange(0, convertToString(user.user_name).length + 1)];
                return mutableAttributedString;
            }];
        }else{
            label.text = sugguestDict[@"text"];
        }
        NSArray *sugguestArr = sugguestDict[@"arr"];
        //    [_emojiLabel setText:tempText];
        for (NSDictionary *item in sugguestArr) {
            NSString *text = item[@"htmlText"];
            int loc = [item[@"realFromIndex"] intValue];
            // 一定要在设置text文本之后设置
            [label addLinkToURL:[NSURL URLWithString:item[@"url"]] withRange:NSMakeRange(loc, text.length)];
        }
    }else{
        if(convertToString(text).length > 0 && user!=nil){
            NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text];
            //文字颜色
            [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName
                                            value:color
                                            range:NSMakeRange(0, convertToString(user.user_name).length + 1)];
            [label setAttributedText:mutableAttributedString];
        }else{
            label.text = text;
        }
    }
}

-(void)addLinkMessage:(ZCTTMLEmojiLabel *) label text:(NSString *)text{
    text = [ZZCoreTools replaceMessageEmoji:text];
    NSString *sugguestText = [ZZCoreTools transformStringAt:text];
//    sugguestText = [ZZCoreTools transformStringGif:sugguestText];
    NSMutableDictionary *sugguestDict = [label getTextADict:sugguestText];
    if(sugguestDict){
        label.text = sugguestDict[@"text"];
        NSArray *sugguestArr = sugguestDict[@"arr"];
        //    [_emojiLabel setText:tempText];
        for (NSDictionary *item in sugguestArr) {
            NSString *text = item[@"htmlText"];
            int loc = [item[@"realFromIndex"] intValue];
            // 一定要在设置text文本之后设置
            [label addLinkToURL:[NSURL URLWithString:item[@"url"]] withRange:NSMakeRange(loc, text.length)];
        }
    }else{
        label.text = sugguestText;
    }
}


// 链接点击
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    DLog(@"链接地址:%@",url.absoluteString);
    [self doLinkClick:url.absoluteString];
    
}

// 链接点击
-(void)ZCMLEmojiLabel:(ZCTTMLEmojiLabel *)emojiLabel didSelectLink:(NSString *)link withType:(ZCTTMLEmojiLabelLinkType)type{
    DLog(@"意外添加的：%@",link);
    [self doLinkClick:link];
}


-(void)doLinkClick:(NSString *) url{
    if([url hasPrefix:@"name://"]){
        return;
    }
    if([url hasPrefix:@"uid://"]){
        UserInfoController *vc = [[UserInfoController alloc] init];
        vc.user_id = [url stringByReplacingOccurrencesOfString:@"uid://" withString:@""];
        if(self.delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
            [self.delegate onCellItemClick:ZZClickOpenVC obj:vc];
        }
    }else{
        if([url hasPrefix:@"tel:"] || validateNumber(url)){
            NSString *callURL = [url stringByReplacingOccurrencesOfString:@"tel:" withString:@""];
            [[AlertUtil shareInstance] showAlert:nil message:callURL cancelTitle:@"取消" titleArray:@[@"呼叫"] viewController:(UIViewController *)self.delegate confirm:^(NSInteger buttonTag) {
                if(buttonTag == 0){
                    // 打电话
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callURL]];
                }
            }];
        }else if([url hasPrefix:@"mailto:"] || validateEmail(url)){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }else{
            if (![url hasPrefix:@"https"] && ![url hasPrefix:@"http"]) {
                url = [@"https://" stringByAppendingString:url];
            }
            
            SVWebViewController *vc = [[SVWebViewController alloc] initWithURL:[NSURL URLWithString:url]];
            if(self.delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
                [self.delegate onCellItemClick:ZZClickOpenVC obj:vc];
            }
        }
    }
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
